package net.xiaosaguo.mymall.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import net.xiaosaguo.common.pojo.dto.es.SkuEsModel;
import net.xiaosaguo.mymall.search.config.ElasticsearchConfig;
import net.xiaosaguo.mymall.search.constant.EsConstant;
import net.xiaosaguo.mymall.search.service.MallSearchService;
import net.xiaosaguo.mymall.search.vo.SearchParam;
import net.xiaosaguo.mymall.search.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: 商品检索
 *
 * @author xiaosaguo
 * @date 2020/06/27
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    RestHighLevelClient esRestClient;

    public static final String URL_SEPARATOR = "_";
    public static final String URL_ARRAY_SEPARATOR = ":";

    @SneakyThrows
    @Override
    public SearchResult search(SearchParam searchParam) {
        // 1. 动态构建出查询需要的 DSL（Domain Specific Language） 语句
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        // 2. 执行检索请求
        SearchResponse searchResponse = esRestClient.search(searchRequest, ElasticsearchConfig.COMMON_OPTIONS);

        // 3. 解析响应数据，封装返回结果
        return buildSearchResult(searchResponse, searchParam);
    }

    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        /*
         * 模糊匹配、过滤（按照属性、分类、品牌、价格区间、库存）
         */
        // 1. 构建 bool query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 1.1 构建 bool-must query
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
        }
        // 1.2 构建 bool-filter query
        // 1.2.1 三级分类过滤
        if (searchParam.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
        }
        // 1.2.2 品牌过滤 brandId=1&brandId=2
        if (searchParam.getBrandId() != null && !searchParam.getBrandId().isEmpty()) {
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        // 1.2.3 属性过滤
        if (searchParam.getAttrs() != null && !searchParam.getAttrs().isEmpty()) {
            for (String attrStr : searchParam.getAttrs()) {
                // attrs=1_安卓:苹果:others&attrs=2_3寸:7寸
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] split = attrStr.split(URL_SEPARATOR);
                String attrId = split[0];
                String[] attrValues = split[1].split(URL_ARRAY_SEPARATOR);
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                NestedQueryBuilder nestedQueryBuilder =
                        QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }
        }
        // 1.2.4 库存过滤 hasStock=0/1
        if (searchParam.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        // 1.2.5 价格区间过滤 skuPrice=1_500/_500/500_
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] split = searchParam.getSkuPrice().split(URL_SEPARATOR);
            if (split.length > 1) {
                rangeQueryBuilder.gte(split[0]).lte(split[1]);
            } else {
                if (searchParam.getSkuPrice().startsWith(URL_SEPARATOR)) {
                    rangeQueryBuilder.lte(split[0]);
                }
                if (searchParam.getSkuPrice().endsWith(URL_SEPARATOR)) {
                    rangeQueryBuilder.gte(split[0]);
                }
            }
            boolQueryBuilder.filter(rangeQueryBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder);

        /*
         * 排序、分页、高亮
         */
        // 2.1 排序 saleCount_asc skuPrice_asc hotScore_asc
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String[] split = searchParam.getSort().split(URL_SEPARATOR);
            searchSourceBuilder.sort(split[0], "asc".equalsIgnoreCase(split[1]) ? SortOrder.ASC : SortOrder.DESC);
        }
        // 2.2 分页
        /*
         * pageNum:1 from:0 size:5 [0,1,2,3,4]
         * pageNum:2 from:1 size:5 [5,6,7,8,9]
         * from = (pageNum - 1) * size
         */
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        // 2.3 高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            searchSourceBuilder.highlighter(
                    new HighlightBuilder()
                            .field("skuTitle")
                            .preTags("<b style='color:red'>")
                            .postTags("</b>")
            );
        }

        /*
         * 聚合分析
         */
        // 3.1 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);
        // 3.2 分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogAgg);
        // 3.3 属性聚合
        NestedAggregationBuilder nestedAttrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(10);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));
        nestedAttrAgg.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAttrAgg);

        System.out.println(searchSourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam request) {
        SearchResult result = new SearchResult();

        // 1. 封装查询到的所有商品
        List<SkuEsModel> skuEsModelList = new ArrayList<>();
        if (response.getHits().getHits() != null && response.getHits().getHits().length > 0) {
            for (SearchHit hit : response.getHits().getHits()) {
                SkuEsModel skuEsModel = JSON.parseObject(hit.getSourceAsString(), SkuEsModel.class);
                if (!StringUtils.isEmpty(request.getKeyword())) {
                    String skuTitle = hit.getHighlightFields().get("skuTitle").getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModelList.add(skuEsModel);
            }
        }
        result.setProducts(skuEsModelList);

        // 2. 当前所有商品涉及到的所有属性信息
        ParsedNested attrAgg = response.getAggregations().get("attr_agg");
        List<SearchResult.AttrVO> attrVOList = new ArrayList<>();
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVO attrVO = new SearchResult.AttrVO();
            attrVO.setAttrId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
            attrVO.setAttrName(attrNameAgg.getBuckets().get(0).getKeyAsString());
            ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValueList = attrValueAgg.getBuckets().stream()
                    .map(MultiBucketsAggregation.Bucket::getKeyAsString)
                    .collect(Collectors.toList());
            attrVO.setAttrValue(attrValueList);
            attrVOList.add(attrVO);
        }
        result.setAttrs(attrVOList);

        // 3. 当前所有商品涉及到的所有品牌信息
        ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVO> brandVOList = new ArrayList<>();
        for (Terms.Bucket bucket : brandAgg.getBuckets()) {
            SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
            brandVO.setBrandId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
            brandVO.setBrandName(brandNameAgg.getBuckets().get(0).getKeyAsString());
            ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
            brandVO.setBrandImg(brandImgAgg.getBuckets().get(0).getKeyAsString());
            brandVOList.add(brandVO);
        }
        result.setBrands(brandVOList);

        // 4. 当前所有商品涉及到的所有分类信息
        ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
        List<SearchResult.CatalogVO> catalogVOList = new ArrayList<>();
        for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
            SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();
            catalogVO.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
            catalogVO.setCatalogName(catalogNameAgg.getBuckets().get(0).getKeyAsString());
            catalogVOList.add(catalogVO);
        }
        result.setCatalogs(catalogVOList);

        // 5. 分页信息-页码、总记录数、总页码
        result.setPageNum(request.getPageNum());
        int total = (int) response.getHits().getTotalHits().value;
        result.setTotal(total);
        result.setTotalPages(total % EsConstant.PRODUCT_PAGESIZE == 0
                ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1);

        return result;
    }
}
